package data_operater

import "fmt"

type Token struct {
	value     string
	tokenType TokenType
}

func parseToken(stateMover *StateMoveManager, path string) ([]Token, error) {
	state := StateStart
	tmpStr := ""
	tokens := make([]Token, 0)
	for _, char := range path {
		if nextStatus, err := stateMover.MoveTo(state, string(char)); err == nil {

			if state == nextStatus {
				tmpStr = tmpStr + string(char)
			} else {
				if nextStatus == StateOpEnd {
					tmpStr = tmpStr + string(char)
					state = nextStatus
					continue
				}
				if state == StateStart {
					state = nextStatus
					tmpStr = tmpStr + string(char)
					continue
				}
				token, err := buildToken(tmpStr, state)
				if err != nil {
					return nil, err
				}
				tokens = append(tokens, token)
				tmpStr = string(char)
				state = nextStatus
			}

		} else {
			return nil, err
		}
	}
	if tmpStr != "" {
		token, err := buildToken(tmpStr, state)
		if err != nil {
			return nil, err
		}
		tokens = append(tokens, token)
	}
	return tokens, nil
}

func NewOpToken(tokenValue string) (Token, error) {
	switch string(tokenValue[0]) {
	case ".":
		return Token{
			tokenType: OpProp,
		}, nil
	case "[":
		return Token{
			tokenType: OpArray,
			value:     tokenValue[1 : len(tokenValue)-1],
		}, nil
	case "|":
		return Token{
			value:     "",
			tokenType: OpMergeField,
		}, nil
	}
	return Token{}, fmt.Errorf("不支持的操作符：%s", tokenValue)
}

func buildToken(tokenValue string, state State) (Token, error) {
	switch state {
	case StateField:
		return Token{
			value:     tokenValue,
			tokenType: Field,
		}, nil
	case StateOpStart, StateOpEnd:
		token, err := NewOpToken(tokenValue)
		return token, err
	}
	return Token{}, fmt.Errorf("不支持的Token：%s", tokenValue)
}
